<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="150px">
      <h2 style="text-align: center">计算机/自动设备校核年度计划</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
            <el-cascader ref="reference" :style="{ width: '100%' }"
              :props="{ value: 'id', checkStrictly: true, multiple: true }" :value-format="valueFormat"
              :show-all-levels="false" placeholder="部门" v-model="formData.deptId" :options="deptOptions"
              @change="changeCascader" @visible-change="visibleChange($event, scope.$index)"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="软件名称" prop="softwareValue">
            <el-select v-model="formData.softwareValue" placeholder="请选择软件名称" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.software_name" :key="dict" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="版本号" prop="versionValue">
            <el-select v-model="formData.versionValue" placeholder="请选择版本号" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.version_code" :key="dict" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="核查方式" prop="checkValue">
            <el-select v-model="formData.checkValue" placeholder="请选择核查方式" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.check_type" :key="dict" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="核查内容" prop="contentValue">
            <el-select v-model="formData.contentValue" placeholder="请选择核查内容" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.check_content" :key="dict" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划实施时间" prop="startTime">
            <el-date-picker v-model="formData.startTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{ width: '100%' }" placeholder="请选择完成日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参加人员" prop="userId">
            <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeUser" placeholder="请选择责任部门负责人"
              v-model="formData.userId"></UserDialogSelection>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"></el-input>
      </el-form-item>
      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";

import {
  autoDeviceYearPlanAdd,
  autoDeviceYearPlanEdit,
  autoDeviceYearPlanInfo,
} from "@/api/quality/computer/plan.js";
import { selectList as selectListplan } from "@/api/quality/manageAudit/plan.js";
export default {
  components: {},
  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  dicts: ['software_name',"version_code", "check_type",'check_content'],
  data() {
    return {
      planList: [],
      formData: {
        content: undefined,
        deptId: undefined,
        sendDate: null,
        startTime: null,
        userId: undefined,
        result: undefined,
        remark: undefined,
        innerManagerAuditId: undefined,
      },
      deptOptions: [],
      deptIdShow: false,
      rules: {
        softwareValue: [
          {
            required: true,
            message: "请选择软件名称",
            trigger: "change",
          },
        ],
        versionValue: [
          {
            required: true,
            message: "请选择版本编号",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择责任部门",
            trigger: "change",
          },
        ],
        checkValue: [
          {
            required: true,
            message: "请选择核查方式",
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请选择计划实施时间",
            trigger: "change",
          },
        ],
        userId: [
          {
            required: false,
            message: "请选择参与人员",
            trigger: "blur",
          },
        ],
        contentValue: [
          {
            required: true,
            message: "请选择核查内容",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
      },
      deptName:'',
      deptId:''
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getDeptTree();


    this.getPlan();
  },
  mounted() { },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
          this.getinfo();
        }
      });
    },
    getPlan() {
      selectListplan().then((response) => {
        this.planList = response.data;
      });
    },
    changeUser(e) {
      console.log(e);
      let idList = []
      let nameList = []
      e.forEach((i) => {
        idList.push(i.userId)
        nameList.push(i.nickName)
      });
      console.log(idList, 'idList');
      this.formData.userId = idList.toString()
      this.formData.userName = nameList.toString()
    },
    changeCascader(e) {
      console.log(this.$refs.reference.getCheckedNodes());
      let arr = this.$refs.reference.getCheckedNodes()
      let list = []
      let label = []
      arr.forEach((item, index) => {
        list.push(item.value)
        label.push(item.label)
        console.log(item.value);
      })
      console.log(list);
      this.deptIdStringValue = list.toString()
      this.deptIdStringLabel = label.toString()
      console.log(this.deptIdStringValue, this.deptIdStringLabel);
      this.deptIdShow = true

    },
    visibleChange(e) {
    },
    getinfo() {
      autoDeviceYearPlanInfo(this.$route.query.id || this.id).then((response) => {
        this.formData = response.data;
        this.deptId = this.formData.deptId
        this.deptName = this.formData.deptName
        this.formData.deptId = this.formData.deptId.split(',')
        // 将ID转number类型
        this.formData.deptId = this.formData.deptId.map(i => parseInt(i))
        console.log(this.formData.deptId);
        let list = []
        // 多选部门回显取后端返回的ID
        this.formData.deptId.map(i => {
          list.push(this.findParentLot(i))
        })
        this.formData.deptId = list
        console.log(this.formData.deptId);
      });
    },
    // 创建新数组 返回
    findParentLot(id) {
      const arr = []
      this.deployIdFun(this.deptOptions, id, arr)
      return arr.reverse()
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id)
          console.log(newArr, 'newArr');
          if (!v.parentId || v.parentId !== '0') {
            this.deployIdFun(this.deptOptions, v.parentId, newArr)
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr)
          }
        }
      })
    },
    submitForm() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          if (this.deptIdShow) {
            query.deptId = this.deptIdStringValue
            query.deptName = this.deptIdStringLabel
          } else {
            query.deptId = this.deptId
            query.deptName = this.deptName
          }

          query.userId = query.userId.toString()
          if (this.formData.innerManagerOptimizeId != undefined) {
            autoDeviceYearPlanEdit(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            autoDeviceYearPlanAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
